package clips

import "C"
import (
	"bytes"
	"errors"
	"github.com/atotto/clipboard"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"ideatools/application/pkgs/mylog"
	"ideatools/application/pkgs/syst"
	"ideatools/pkg/kb_event"
	"io/ioutil"
	"os/exec"
	"runtime"
	"time"
)

func SetText(content string) error {
	err := clipboard.WriteAll(content)
	if err != nil {
		mylog.Error("SetText() 写入剪贴板异常" + err.Error())
		return err
	}

	return nil
}

func GetLeastText() (string, error) {

	if runtime.GOOS == syst.SystemTypeWindows {
		return clipboard.ReadAll()
	}

	if runtime.GOOS == syst.SystemTypeMac {
		return getPastedContentMac()
	}

	return "", errors.New("操作系统不支持")

}
func getPastedContentMac() (string, error) {
	pasteCmd := exec.Command("pbpaste")
	out, err := pasteCmd.Output()
	if err != nil {
		return "", err
	}
	//如果中文没乱码 直接返回

	decoder := simplifiedchinese.GBK.NewDecoder()
	transformer := transform.NewReader(bytes.NewReader(out), decoder)
	transformedOut, _ := ioutil.ReadAll(transformer)
	return string(transformedOut), nil
}

// CopySelect 复制系统选中的文本
func CopySelect() {

	if runtime.GOOS == syst.SystemTypeMac {
		CopySelectMac()
	}

	if runtime.GOOS == syst.SystemTypeWindows {
		CopySelectWindow()
	}

}

// Parse 执行粘贴命令
func Parse() {
	if runtime.GOOS == syst.SystemTypeMac {
		parseMac()
	}

	if runtime.GOOS == syst.SystemTypeWindows {
		parseWin()
	}
}

func CopySelectWindow() {
	kb, err := kb_event.NewKeyBonding()
	if err != nil {
		mylog.Error("CopySelectMac error" + err.Error())
		return
	}
	// Select keys to command+c
	kb.HasCTRL(true) //(win键)
	time.Sleep(10 * time.Millisecond)
	kb.SetKeys(kb_event.VK_C)
	err = kb.Launching()
	// Or you can use Press and Release
	kb.Press()
	time.Sleep(10 * time.Millisecond)
	kb.Release()
}

func CopySelectMac() {
	kb, err := kb_event.NewKeyBonding()
	if err != nil {
		mylog.Error("CopySelectMac error" + err.Error())
		return
	}
	// Select keys to command+c
	kb.HasSuper(true) //(win键)
	time.Sleep(10 * time.Millisecond)
	kb.SetKeys(kb_event.VK_C)
	err = kb.Launching()
	// Or you can use Press and Release
	kb.Press()
	time.Sleep(10 * time.Millisecond)
	kb.Release()
}

func parseWin() {
	kb, err := kb_event.NewKeyBonding()
	if err != nil {
		mylog.Error("parseMac()  error" + err.Error())
		return
	}
	// Select keys to command+c
	kb.HasCTRL(true) //(win键)
	//time.Sleep(10 * time.Millisecond)
	kb.SetKeys(kb_event.VK_V)
	err = kb.Launching()
	// Or you can use Press and Release
	//kb.Press()
	//time.Sleep(10 * time.Millisecond)
	kb.Release()
}

func parseMac() {
	kb, err := kb_event.NewKeyBonding()
	if err != nil {
		mylog.Error("parseMac()  error" + err.Error())
		return
	}
	// Select keys to command+c
	kb.HasSuper(true) //(win键)
	//time.Sleep(10 * time.Millisecond)
	kb.SetKeys(kb_event.VK_V)
	err = kb.Launching()
	// Or you can use Press and Release
	//kb.Press()
	//time.Sleep(10 * time.Millisecond)
	kb.Release()
}
